var app = getApp();
var ajax = require('../../utils/ajax.js');
var common = require('../../utils/common.js');
var MPage = require('../MPage.js');
var begin_time = "";
var end_time = "";

Page(common.extendPage(MPage, {
    data: {
        dataLoaded: false,
        loading: false,
        moreLoading: false,
        currentTab: 0,
        couponList: [],
        page: 1,
        noMore: false,
    },

    onShow: function() {
        var self = this;
        self._toTab(0, function() {
            self.setData({
                dataLoaded: true,
            });
        });
    },
    /**
     * 事件切换tab
     */
    _tabSwitch: function(evt) {
        var formId = evt.detail.formId;
        var index = +evt.currentTarget.dataset.current;
        this._toTab(index);
        common.submitForm(formId);
    },

    _toTab: function(index, cb) {
        this.setData({
            currentTab: index,
            couponList: [],
            page: 1,
            noMore: false,
        });
        this._getCouponList({
            ty: index
        }, cb);
    },

    _getCouponList: function(params, cb) {
        var self = this;
        var ty = params.ty;
        var isMore = params.isMore;
        var page = self.data.page || 1;
        var url = '/openapi/CCoupon/getMyCoupon';
        if (isMore) {
            self.setData({
                moreLoading: true
            });
        } else {
            self.setData({
                loading: true
            });
        }
        ajax.P(url, {
            type: ty,
            page: page
        }, function(data) {
            var couponList = data.result.couponList || [];

            couponList.forEach(function(coupon) {
                var money = parseInt(coupon.coupon_amount);
                if (money == coupon.coupon_amount) {
                    coupon.coupon_amount = money;
                }
            });

            var toData = {
                couponList: self.data.couponList.concat(couponList),
                noMore: couponList.length == 0,
                page: self.data.page + 1,
            };
            toData[isMore ? 'moreLoading' : 'loading'] = false;
            self.setData(toData);
            cb && cb();
        });
    },
    /**
     * 加载更多
     */
    _loadMore: function() {
        if (this.data.moreLoading || this.data.loading || this.data.noMore) {
            return;
        }
        this._getCouponList({
            ty: this.data.currentTab,
            isMore: true
        });
    },
    _jump: function(evt) {
        common.jump(evt);
    }
}));